﻿using System;
using System.Threading;
using EzPos.Model.Common;
using EzPos.Service;
using EzPos.GUIs.Forms;
using EzPos.Properties;
using System.Windows.Forms;
using EzPos.Service.Common;
using EzPos.Service.Expense;
using EzPos.Service.Report;
using EzPos.Service.SaleOrder;
using EzPos.Service.User;
using Application = System.Windows.Forms.Application;
using ExcelApplication = Microsoft.Office.Interop.Excel.Application;

namespace EzPos.GUIs.Controls
{
    public partial class CtrlReport : UserControl
    {
        private ReportService _reportService;
        private ExpenseService _expenseService;
        private SaleOrderService _saleOrderService;

        public CtrlReport()
        {
            InitializeComponent();
        }

        public SaleOrderService SaleOrderService
        {
            set { _saleOrderService = value; }
        }

        public ExpenseService ExpenseService
        {
            set { _expenseService = value; }
        }

        private void RefreshReportSale()
        {
            if (chbShowBenefit.Checked)
            {
                if (!UserService.AllowToPerform(Resources.PermissionViewSaleDetailReport))
                {
                    const string briefMsg = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
                    var detailMsg = Resources.MsgUserPermissionDeny;
                    using (var frmMessageBox = new FrmExtendedMessageBox())
                    {
                        frmMessageBox.BriefMsgStr = briefMsg;
                        frmMessageBox.DetailMsgStr = detailMsg;
                        frmMessageBox.IsCanceledOnly = true;
                        frmMessageBox.ShowDialog(this);
                        return;
                    }
                }
            }
            else
            {
                if (!UserService.AllowToPerform(Resources.PermissionViewSaleReport))
                {
                    const string briefMsg = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
                    var detailMsg = Resources.MsgUserPermissionDeny;
                    using (var frmMessageBox = new FrmExtendedMessageBox())
                    {
                        frmMessageBox.BriefMsgStr = briefMsg;
                        frmMessageBox.DetailMsgStr = detailMsg;
                        frmMessageBox.IsCanceledOnly = true;
                        frmMessageBox.ShowDialog(this);
                        return;
                    }
                }
            }

            RefreshSaleStatementReport();
        }

        private void BtnSearchSaleClick(object sender, EventArgs e)
        {
            try
            {
                if (!UserService.AllowToPerform(Resources.PermissionByDatesReport))
                {
                    if ((!dtpStartDate.Value.Date.Equals(DateTime.Today)) || (!dtpStopDate.Value.Date.Equals(DateTime.Today)))
                    {
                        const string briefMsg = "សិទ្ធមើល របាយការណ៏តាមថ្ងៃ";
                        var detailMsg = Resources.MsgUserPermissionDeny;
                        using (var frmMessageBox = new FrmExtendedMessageBox())
                        {
                            frmMessageBox.BriefMsgStr = briefMsg;
                            frmMessageBox.DetailMsgStr = detailMsg;
                            frmMessageBox.IsCanceledOnly = true;
                            frmMessageBox.ShowDialog(this);
                            return;
                        }
                    }                    
                }

                wbsReport.BringToFront();
                if (rdbSale.Checked)
                    RefreshReportSale();
                else if (rdbExpense.Checked)
                    RefreshDailyExpenseReport();
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            }
        }

        private void BtnSearchSaleMouseEnter(object sender, EventArgs e)
        {
            btnSearchSale.BackgroundImage = Resources.background_9;
        }

        private void BtnSearchSaleMouseLeave(object sender, EventArgs e)
        {
            btnSearchSale.BackgroundImage = null;
        }

        private void RefreshDailyExpenseReport()
        {
            if (!UserService.AllowToPerform(Resources.PermissionViewExpenseReport))
            {
                const string briefMsg = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
                var detailMsg = Resources.MsgUserPermissionDeny;
                using (var frmMessageBox = new FrmExtendedMessageBox())
                {
                    frmMessageBox.BriefMsgStr = briefMsg;
                    frmMessageBox.DetailMsgStr = detailMsg;
                    frmMessageBox.IsCanceledOnly = true;
                    frmMessageBox.ShowDialog(this);
                    return;
                }
            }

            try
            {
                _reportService.ExpenseService = _expenseService;
                var reportFileName = _reportService.ExpenseStatementReport(
                    dtpStartDate.Value.ToString("dd/MM/yyyy", AppContext.CultureInfo),
                    dtpStopDate.Value.ToString("dd/MM/yyyy", AppContext.CultureInfo));

                OpenReport(reportFileName);
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            } 
        }

        private void CtrlReport_Load(object sender, EventArgs e)
        {
            if (_saleOrderService == null)
                _saleOrderService = ServiceFactory.GenerateServiceInstance().GenerateSaleOrderService();
            if (_expenseService == null)
                _expenseService = ServiceFactory.GenerateServiceInstance().GenerateExpenseService();
            if (_reportService == null)
                _reportService = new ReportService();

            try
            {                
                ThreadStart threadStart = RemoveTemporaryFiles;
                var thread = new Thread(threadStart) { IsBackground = true };
                thread.Start();
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            }
        }

        private static void RemoveTemporaryFiles()
        {
            try
            {
                CommonService.DeleteFile(
                    Application.StartupPath,
                    Resources.ConstSaleStatementExcelFile,
                    "*.xlsx*",
                    true);
            }
// ReSharper disable EmptyGeneralCatchClause
            catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
            {
                //Do nothing
            }
        }

        private void RefreshSaleStatementReport()
        {
            try
            {                
                _reportService.SaleOrderService = _saleOrderService;
                var reportFileName = _reportService.SaleStatementReport(
                    dtpStartDate.Value.ToString("dd/MM/yyyy", AppContext.CultureInfo),
                    dtpStopDate.Value.ToString("dd/MM/yyyy", AppContext.CultureInfo));

                OpenReport(reportFileName);
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            }            
        }

        private void OpenReport(string reportFileName)
        {
            try
            {
                if (string.IsNullOrEmpty(reportFileName))
                {
                    var briefMsg = Resources.MsgExtendedCaptionFind;
                    var detailMsg = Resources.MsgSearchResultEmpty;
                    using (var frmMessageBox = new FrmExtendedMessageBox())
                    {
                        frmMessageBox.BriefMsgStr = briefMsg;
                        frmMessageBox.DetailMsgStr = detailMsg;
                        frmMessageBox.IsCanceledOnly = true;
                        frmMessageBox.ShowDialog(this);
                        return;
                    }
                }

                //Open report
                wbsReport.Navigate("about:blank");

                //var excelApplication = new ExcelApplication();
                //var workBook = excelApplication.Workbooks.Open(
                //    reportFileName,
                //    0,
                //    false,
                //    5,
                //    false,
                //    string.Empty,
                //    false,
                //    XlPlatform.xlWindows,
                //    string.Empty,
                //    true,
                //    false,
                //    0,
                //    true,
                //    false,
                //    false);

                wbsReport.BringToFront();
                wbsReport.Navigate(reportFileName);
            }
            catch(Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);                
            }
        }
    }
}